package io.renren.modules.cli.service.impl;

import io.renren.common.utils.Constant;
import io.renren.modules.cli.dao.CliMenuDao;
import io.renren.modules.cli.dao.CliUserDao;
import io.renren.modules.cli.dao.CliUserTokenDao;
import io.renren.modules.cli.entity.CliMenuEntity;
import io.renren.modules.cli.entity.CliUserEntity;
import io.renren.modules.cli.entity.CliUserTokenEntity;
import io.renren.modules.cli.service.CliShiroService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class CliShiroServiceImpl implements CliShiroService {
    @Autowired
    private CliMenuDao cliMenuDao;
    @Autowired
    private CliUserDao cliUserDao;
    @Autowired
    private CliUserTokenDao cliUserTokenDao;

    @Override
    public Set<String> getUserPermissions(long userId) {
        List<String> permsList;

        //系统管理员，拥有最高权限
        if(userId == Constant.SUPER_ADMIN){
            List<CliMenuEntity> menuList = cliMenuDao.selectList(null);
            permsList = new ArrayList<>(menuList.size());
            for(CliMenuEntity menu : menuList){
                permsList.add(menu.getPerms());
            }
        }else{
            permsList = cliUserDao.queryAllPerms(userId);
        }
        //用户权限列表
        Set<String> permsSet = new HashSet<>();
        for(String perms : permsList){
            if(StringUtils.isBlank(perms)){
                continue;
            }
            permsSet.addAll(Arrays.asList(perms.trim().split(",")));
        }
        return permsSet;
    }

    @Override
    public CliUserTokenEntity queryByToken(String token) {
        return cliUserTokenDao.queryByToken(token);
    }

    @Override
    public CliUserEntity queryUser(Long userId) {
        return cliUserDao.selectById(userId);
    }
}
